package com.sto.stoapp.thread;

import android.content.Context;
import android.util.Log;

import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.BillControls;
import com.sto.stoapp.jpush.HttpGetControls;
import com.sto.stoapp.util.BillControlsUtil;
import com.sto.stoapp.util.NetUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wj on 2016-12-29.
 *
 * 扫描管控线程
 */

public class BillControlsThread extends Thread{

    /**
     * 网点编号
     */
    private String orgCode;
    private Context context;

    public BillControlsThread(String orgCode ,Context context){
        this.orgCode=orgCode;
        this.context=context;
    }

    @Override
    public void run() {
        super.run();

        //判断是否有网络连接
        if(!NetUtil.isNetworkAvailable(context)){
            return;
        }

        String lastTime=StoFilePreference.getInstance(context).getControlsTime();
        if("".equals(lastTime)){
            //第一次访问，取6个月之前的时间
            lastTime= BillControlsUtil.get6MothAgoTime();
        }

        String netCode=StoFilePreference.getInstance(context)
                .getSiteCode();

        String result=HttpGetControls.getControls(netCode,lastTime);

        if(result==null || "".equals(result))
            return;

        Log.e("wj","扫描管控获取到的数据："+result);
        BillControls bean=BillControlsUtil.str2Entity(result);

        if(null!=bean){
            //保存扫描管控开关
            StoFilePreference.getInstance(context).setControlsOnOff(bean.isInterceptOnOff());

            List<BillControls.RulesBean> list=new ArrayList<BillControls.RulesBean>();

            //先获取本地管控规则
            String oldRules=StoFilePreference.getInstance(context).getControlsRules();
            List<BillControls.RulesBean> oldList = BillControlsUtil.str2List(oldRules);
            if(null!=oldList && oldList.size()>0){
                //过滤旧数据
                List<BillControls.RulesBean> fillterdList=BillControlsUtil.fillterList(oldList);
                list.addAll(fillterdList);
            }

            if(bean.getRules().size()>0){
                //保存获取时间
                list.addAll(bean.getRules());
                String endTime=bean.getRules().get(bean.getRules().size()-1).getEndTime();
                StoFilePreference.getInstance(context).setControlsTime(endTime);
            }

            //保存管控数据
            String listStr=BillControlsUtil.list2Str(list);
            StoFilePreference.getInstance(context).setControlsRules(listStr);
        }
    }
}
